﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

using Socium.Domain.Collections;
using Socium.Domain.Persons;
using Socium.Domain.Tests.Sociometric;

namespace Socium.Testings.Sociometric {
	class ElectionCellViewModel : CellViewModel {
		readonly ProcedureViewModel _procedure_view_model;

		readonly Person _elector;
		readonly Person _elected;

		public ElectionCellViewModel(ProcedureViewModel procedure_view_model, Person elector, Person elected, IEnumerable<Election> elections, IDictionary<ElectionCriteria, ElectionCriteriaViewModel> dictionary) : base(GetDisplayName(elector, elected)) {
			_procedure_view_model = procedure_view_model;

			_elector = elector;
			_elected = elected;

			var query =
				from election in elections
				where election.Elector == elector && election.Elected == elected
				select new {Election = election, ViewModel = dictionary[election.ElectionCriteria]};

			var election_view_models =
				from entry in query
				select new ElectionViewModel(entry.Election, entry.ViewModel);

			_elections.AddRange(election_view_models);
		}

		static string GetDisplayName(Person elector, Person elected) {
			return string.Format("{0} - {1}", elector, elected);
		}

		readonly ObservableCollection<ElectionViewModel> _elections = new ObservableCollection<ElectionViewModel>();

		public ICollection<ElectionViewModel> Elections {
			get { return _elections; }
		}

		public void Click() {
			var criteria = _procedure_view_model.SelectedCriteria;
			if (criteria == null) {
				return;
			}

			var view_models = _elections.Filter(e => e.ElectionCriteria == criteria);
			if (view_models.Count > 0) {
				view_models.Iterate(view_model => _procedure_view_model.Delete(view_model));
				view_models.Iterate(view_model => _elections.Remove(view_model));
			}
			else {
				var election = new Election(_elector, _elected, criteria.ElectionCriteria, 0);
				_procedure_view_model.Add(election);
				var view_model = new ElectionViewModel(election, criteria);
				_elections.Add(view_model);
			}
		}

		public override bool IsClickable {
			get { return true; }
		}
	}
}
